#include <iostream>
#include <time.h>
#include "socket.hpp"
#include "Protocol.hpp"

void Usage(std::string s)
{
    std::cout << s << "  [ip : port]" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    Sock sock;
    sock.Socket();
    bool r = sock.Connect(ip, port);
    if (!r)
        return 1;

    int cnt = 1;
    srand(time(nullptr));
    while ((cnt++) <= 5)
    {
        std::cout << "-------------------------第" << cnt - 1 << "次运算" << "----------------" << std::endl;
        int x = rand() % 100 + 1;
        int y = rand() % 100;
        std::string opers = "+-*/%^=!";
        char op = opers[rand() % opers.size()];

        std::cout << "quest: " << x << op << y << "=?" << std::endl;
        Request req(x, y, op);
        std::string content;
        req.Serialization(&content);
        std::string send_pack = Encode(content);

        write(sock.Getfd(), send_pack.c_str(), send_pack.size());

        std::string recv_pack;
        char inbuffer[1024];
        ssize_t s = read(sock.Getfd(), inbuffer, sizeof(inbuffer));
        if (s > 0)
        {
            inbuffer[s] = 0;
            recv_pack += inbuffer;
            Decode(recv_pack, &content);
            

            Response resp;
            resp.Deserialization(content);

            std::cout << "return result: " << resp._result << ", " << resp._code << std::endl;
        }
        std::cout << "----------------------------------------------------------------" << std::endl;

    }
    sock.Close();
    return 0;
}